import { Modal, message } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { Ref, computed, createVNode } from "vue";
import {
  getListApi,
  getLogApiByWaybillApi,
  getPageStaticApi,
  revocationQuotationApi,
  orderShipmentQuotationExcelApi,
  getCombinedWaybillsApi
} from "@/api/waybillManagement/businessWaybill/waybillQuotation";
import dayjs from "dayjs";
// import CommonHook from "@/hook/commonHook";
export default function OperationHook(state: {
  searchForm: WaybillQuotation.SearchForm;
  tableData: Ref<Array<WaybillQuotation.ListRows>>;
  drawerOpts: Base.DrawerOpts;
  dialogOpts: Base.DialogOpts;
  loading: Ref<boolean>;
  tableRef: any;
  pageStat: Ref<Base.GeneraDataType>;
  activeKey: Ref<string>;
}) {
  const { searchForm, tableData, drawerOpts, loading, tableRef, dialogOpts, pageStat, activeKey } = state;
  const selectRows = computed<Array<WaybillQuotation.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  // const { getNoZeroKey } = CommonHook();
  const getData = () => {
    const params: any = {
      ...getParams(),
      detentionStatus: null,
      state: Number(activeKey.value)
    };
    loading.value = true;
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
          searchForm.beforePageNum = searchForm.pageNum;
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = getParams();
    return getPageStaticApi({ ...params }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, {
          1: data[1],
          2: data[2],
          3: data[3],
          4: data[4],
          5: data[5]
        });
        // activeKey.value = String(getNoZeroKey(pageStat.value, ["1", "2", "3", "4", "5"]));
        // activeKey.value = "2";
      }
    });
  };
  const getParams = () => {
    const {
      keyWordsList,
      bizIdList,
      customerIdList,
      companyName,
      customerName,
      addressTypeList,
      waybillNums,
      state,
      pageNum,
      pageSize,
      beforePageNum,
      companyIdList,
      channelIdList,
      accountPeriodIdList,
      depositTime,
      billingMethodList
    } = searchForm;
    const params: Parameters<typeof getListApi>[0] = {
      billingMethodList,
      keyWordsList: [],
      bizIdList,
      state,
      companyName,
      customerName,
      addressTypeList,
      waybillNums: [],
      depositStartTime: depositTime.length ? dayjs(depositTime[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      depositEndTime: depositTime.length ? dayjs(depositTime[1]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      customerIdList,
      pageNum,
      pageSize,
      beforePageNum,
      companyIdList,
      channelIdList,
      accountPeriodIdList
    };
    if (keyWordsList)
      params.keyWordsList = keyWordsList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (waybillNums)
      params.waybillNums = waybillNums
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (channelIdList.length) {
      params.channelIdList = channelIdList.map((t: any) => t[t.length - 1]);
    }

    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = async () => {
    getData();
  };
  const offerHandle = (row: WaybillQuotation.ListRows) => {
    drawerOpts.title = `报价`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Offer";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const showHandle = (row: SingleOrderApproval.ListRows) => {
    drawerOpts.title = `运单详情`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const offerDetailsHandle = (row: WaybillQuotation.ListRows) => {
    drawerOpts.title = `报价详情`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "OfferDetails";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 修改渠道
  const modifyChannelHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    if (selectRows.value.length > 1) return message.error("只能勾选1条运单!");
    dialogOpts.title = `修改渠道`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyChannel";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改品名
  const modifyProductNameHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    if (selectRows.value.length > 1) return message.error("只能勾选1条运单!");
    dialogOpts.title = `修改品名`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyProductName";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改材质
  const modifyMasterialHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    if (selectRows.value.length > 1) return message.error("只能勾选1条运单!");
    dialogOpts.title = `修改材质`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyMasterial";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改客户备注
  const modifyRemarkHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    dialogOpts.title = `修改客户备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "BatchModifyRemark";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 修改客户备注
  const modifyInnerRemarkHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    dialogOpts.title = `修改内部备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 2;
    dialogOpts.component = "BatchModifyRemark";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 批量导出
  const batchExportHandle = () => {
    const params = {
      ...getParams(),
      detentionStatus: null,
      state: Number(activeKey.value),
      list: selectRows.value.length ? selectRows.value : []
    };
    return orderShipmentQuotationExcelApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
      }
    });
  };
  const revocationQuotationHandle = (row: WaybillQuotation.ListRows) => {
    Modal.confirm({
      title: "是否撤回当前报价?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        return revocationQuotationApi({ id: row.orderShipmentQuotationId }).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 查看日志
  const showLogHandle = (row: WaybillQuotation.ListRows) => {
    drawerOpts.title = `报价日志`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "OperationLog";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 获取日志
  const getLogFn = () => {
    return getLogApiByWaybillApi({ waybillNums: [drawerOpts.passData?.waybillNum] });
  };

  // 合并报关
  const customsClearanceHandle = () => {
    const billingMethod = Array.from([...new Set(selectRows.value.map((t: any) => t.billingMethod))]);
    if (billingMethod.includes(2)) return message.error("只可选择单票计费进行合并报关!");

    const customerName = Array.from([...new Set(selectRows.value.map((t: any) => t.customerName))]);
    if (customerName.length > 1) return message.error("合并报关仅限同一客户下操作!");

    const channelId = Array.from([...new Set(selectRows.value.map((t: any) => t.channelId))]);
    if (channelId.length > 1) return message.error("合并报关仅限同一渠道下操作!");

    if (!selectRows.value.length) return message.error("请勾选运单!");
    if (selectRows.value.length < 2) return message.error("请至少勾选2个运单方可合并报关!");

    dialogOpts.title = `合并报关`;
    dialogOpts.width = "500px";
    dialogOpts.type = 1;
    dialogOpts.component = "CustomsClearance";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };

  // 取消合并报关
  const cancelMergeDeclarationHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    if (selectRows.value.length > 1) return message.error("只能勾选1条运单!");

    getCombinedWaybillsApi({ billingWaybillNum: selectRows.value[0].billingWaybillNum }).then((res: any) => {
      const { code, data } = res;
      if (code === 200 && data.billingWaybillNum) {
        dialogOpts.title = `取消合并报关`;
        dialogOpts.width = "500px";
        dialogOpts.type = 2;
        dialogOpts.component = "CustomsClearance";
        dialogOpts.passData = selectRows.value;
        dialogOpts.visible = true;
      } else {
        return message.error("运单暂无合并报关信息!");
      }
    });
  };

  //详情
  const MergeDeclarationDetailHandle = (row: WaybillQuotation.ListRows) => {
    dialogOpts.title = `合并报关详情`;
    dialogOpts.width = "500px";
    dialogOpts.type = 3;
    dialogOpts.component = "CustomsClearance";
    dialogOpts.passData = [row];
    dialogOpts.visible = true;
  };

  return {
    searchHandle,
    getData,
    showHandle,
    changeTabHandle,
    modifyChannelHandle,
    modifyMasterialHandle,
    modifyProductNameHandle,
    modifyRemarkHandle,
    modifyInnerRemarkHandle,
    offerHandle,
    offerDetailsHandle,
    revocationQuotationHandle,
    showLogHandle,
    getLogFn,
    batchExportHandle,
    customsClearanceHandle,
    cancelMergeDeclarationHandle,
    MergeDeclarationDetailHandle
  };
}
